/*
 * Created by 岱青海蓝信息系统(北京)有限公司 on 17-6-6 下午3:21
 * Copyright (c) 2017. All rights reserved.
 */

package com.example.dqhl.recycleviewdemo.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.View;

/**
 * 作者：Mark.Han
 * 时间：2016/12/12 17:18.
 * 版本：1.0
 * 描述：
 */

public class LoveView extends View {

    private int offsetX, offsetY;

    private Paint paint;
    private boolean isDrawing = false;
    private float angle = 10L;
    private Path path;

    public LoveView(Context context) {
        this(context, null);
    }

    public LoveView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LoveView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initPaint();

    }

    private Point getHeartPoint(float angle) {
        /**
         * 心形曲线
         * x=16×sin3α
         * y=13×cosα−5×cos2α−2×cos3α−cos4α
         */
        float t = (float) (angle / Math.PI);
        float x = (float) (12.5 * (16 * Math.pow(Math.sin(t), 3)));
        float y = (float) (-15 * (13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t)));
        return new Point(offsetX + (int) x, offsetY + (int) y);
    }

    private void initData() {
        offsetX = getWidth() / 2;
        offsetY = getHeight() / 2 - 55;
    }


    private void initPaint() {
        paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStrokeWidth(2.0f);
        //抗锯齿
        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setStyle(Paint.Style.STROKE);

        path = new Path();

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        initData();
        Point p = getHeartPoint(angle);
        if (!isDrawing) {
            path.moveTo(p.x, p.y);
        }
        path.lineTo(p.x, p.y);
        canvas.drawPath(path, paint);

        onDrawNewThread();
    }

    private void onDrawNewThread() {
        new Thread() {
            @Override
            public void run() {
                if (isDrawing) return;
                isDrawing = true;

                while (angle < 180) {
                    angle = angle + 0.02f;
                    postInvalidate();
                    try {
                        sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
//                isDrawing = false;
            }
        }.start();

    }
}
